package com.karson.kafka.ch02;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringSerializer;

import java.util.Properties;

/**
 * @author Karson Wang
 * @title KafkaProducerAnalysis
 * @Description 描述
 * @Date 2020/4/24 13:53
 * @Copyright 2019-2020
 */
public class KafkaProducerAnalysis {

    public static final String brokerList = "node1:9092";
    public static final String topic = "topic-demo";

    public static void main(String[] args) {
        Properties properties = initConfig();
        // 配置生产者客户端参数并创建KafkaProducer实例
        KafkaProducer<String, String> producer = new KafkaProducer<String, String>(properties);

        // 构建发送消息
        ProducerRecord<String, String> record = new ProducerRecord<>(topic, "Hello, Kafka!");

        // 发送消息
        producer.send(record);

        // 关闭生产者客户端实例
        producer.close();
    }

    public static Properties initConfig() {
        Properties properties = new Properties();
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, brokerList);
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        properties.put(ProducerConfig.CLIENT_ID_CONFIG, "producer.client.id.demo");
        return properties;
    }
}
